<template>
  <back-btn></back-btn>
  <div id="app">
    <h2>监听一个ref</h2>
    <input type="text" v-model="name" />
    <h2>监听一个reactive</h2>
    名称：<input type="text" v-model="info.name" /> 
    品牌：<input type="text" v-model="info.brand" /> 
    尺寸：<input type="text" v-model="info.size" />
    <h2>监听一个getter函数</h2>
    <input type="text" v-model="getter.num" />
    <h2>监听以上类型值组成的数组</h2>
    ref: <input type="text" v-model="age" /> reactive: <input type="text" v-model="user.name" />

    <h2>watchEffect</h2>
    <input type="text" v-model="count" />
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, watch, watchEffect } from "vue";

export default defineComponent({
  setup() {
    // 监听一个ref
    const name = ref("温情");
    watch(name, (newV, oldV) => {
      console.log(`ref发生变化新值为${newV}, 老值为${oldV}`);
    });

    // 监听一个reactive对象  当直接侦听一个响应式对象时，侦听器自动处于深层级模式：
    const info = reactive({
      name: "笔记本电脑",
      brand: "Dell",
      size: 7,
    });
    watch(info, (newV, oldV) => {
      console.log(`reactive对象发生变化`);
    });

    // 监听一个getter函数
    const getter = reactive({ num: 1 });
    watch(
      () => getter.num,
      (newV, oldV) => {
        console.log(`getter函数发生变化新值为${newV}, 老值为${oldV}`);
      }
    );

    // 监听以上类型值组成的数组
    const age = ref(22);
    const user = reactive({
      name: "兰陵王",
      tel: "12345",
    });
    watch(
      [age, user],
      (newV, oldV) => {
        console.log("监听的数组发生变化");
        console.log("newV", newV);
        console.log("oldV", oldV);
      },
      { immediate: true }
    );

    // 只要count发生变化就会执行一次回调
    const count = ref(0);
    const countWatch = watchEffect((newV) => {
      console.log("watchEffect回调触发", count.value);
    });
    count.value++;
    onMounted(() => {
      countWatch();
    });

    return { name, info, getter, age, user, count };
  },
});
</script>

<style scoped></style>
